package com.dk.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("login")
public class LoginController {
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("login")
    public String login(String userName, String password, Model model){
        //借助shiro登录
        //1.创建subject
        Subject subject = SecurityUtils.getSubject();
        //2.封装token
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        //3.调用subject的login 方法
        try{
            subject.login(token);
        }catch (UnknownAccountException e1){
            System.out.println("账号不存在");
            model.addAttribute("mesg","账号不存在");
            return "login";
        }catch (IncorrectCredentialsException e2){
            System.out.println("密码错误");
            model.addAttribute("mesg","密码错误");
        }


        return "redirect:/index";
    }
    @RequestMapping("unauthorized")
    public String unauthorized(Model model){
        model.addAttribute("mesg","抱歉 权限不够");
        return "unauthorized";
    }
}

